package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go_src/common"
	"go_src/dao"
	"strconv"
	"strings"
	"time"
)

func GetAnnouncementList(c *gin.Context) {

	a := dao.Announcement{}

	pagination := common.Pagination{Total: 1, TotalPage: 1, PerPage: 1, CurrentPage: 1}
	_ = c.ShouldBind(&pagination)
	_ = c.ShouldBind(&a)
	announcementResult := a.SelectAnnouncement(&pagination)

	if announcementResult.Success {
		result := make(map[string]interface{})
		result["data"] = announcementResult.Data
		result["pagination"] = pagination
		c.JSON(200, gin.H{"message": "成功", "status": "success", "result": result})
	} else {
		c.JSON(200, gin.H{"message": "失败", "status": "error", "result": nil})
	}

}

func UpdateAnnouncement(c *gin.Context) {

	a := dao.Announcement{UpdateAt: time.Now().UnixNano() / 1e6}
	_ = c.ShouldBind(&a)
	dbResult := a.UpdateAnnouncementById()

	if dbResult.Success {
		c.JSON(200, gin.H{"message": "成功", "status": "success", "result": a})
	} else {
		c.JSON(200, gin.H{"message": "失败", "status": "error"})
	}

}

func SaveAnnouncement(c *gin.Context) {

	a := dao.Announcement{CreateAt: time.Now().UnixNano() / 1e6, UpdateAt: time.Now().UnixNano() / 1e6}

	_ = c.ShouldBind(&a)
	dbResult := a.SaveAnnouncement()

	if dbResult.Success {
		c.JSON(200, gin.H{"message": "成功", "status": "success", "result": a})
	} else {
		c.JSON(200, gin.H{"message": "失败", "status": "error"})
	}

}

func DeleteAnnouncement(c *gin.Context) {

	a := dao.Announcement{}
	ids := strings.Split(c.Param("ids"), ",")
	if len(ids) == 0 {
		c.JSON(200, gin.H{"message": "失败", "status": "error"})
	}

	var dbResult common.Result
	if len(ids) == 1 {
		a.Id, _ = strconv.ParseUint(ids[0], 10, 64)
		dbResult = a.DeleteAnnouncementById()
	} else{
		fmt.Println(ids)
		dbResult = a.BatchDeleteAnnouncementsByIds(ids)
	}

	if dbResult.Success {
		c.JSON(200, gin.H{"message": "成功", "status": "success", "result": a})
	} else {
		c.JSON(200, gin.H{"message": "失败", "status": "error"})
	}

}
